package com.wyw.function.learning.common;

import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

/**
 * @Title   没有先后顺序
 * @Description
 * @Author Mr Wu yewen.wu.china@gmail.com
 * Update History:
 * Author        Time            Content
 */
public class MergeInfoService2 {

    private OrderService orderService = new OrderService();
    private MailService mailService = new MailService();
    private RefundService refundService = new RefundService();

    public MergeInfoVO getInfo(String orderId) {

        // 基于并行编排的查询流程
        // 没有优先级
        // |---stage1---|
        // |---stage2---| ----- stage4
        // |---stage3---|
        try {
            MergeInfoVO mergeInfoVO = new MergeInfoVO();
            CompletableFuture.allOf(
                    CompletableFuture.runAsync(() -> log(() -> buildByOrder(mergeInfoVO, orderService.queryByOrderId(orderId)))),
                    CompletableFuture.runAsync(() -> log(() -> buildByMail(mergeInfoVO, mailService.queryByOrderId(orderId)))),
                    CompletableFuture.runAsync(() -> log(() -> buildByRefund(mergeInfoVO, refundService.queryByOrderId(orderId))))
            ).get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    private MergeInfoVO buildByOrder(MergeInfoVO mergeInfoVO, OrderVO orderVO) {
        mergeInfoVO.setOrderVO(orderVO);
        return mergeInfoVO;
    }

    private MergeInfoVO buildByMail(MergeInfoVO mergeInfoVO, MailVO mailVO) {
        mergeInfoVO.setMailVO(mailVO);
        return mergeInfoVO;
    }

    private MergeInfoVO buildByRefund(MergeInfoVO mergeInfoVO, RefundVO refundVO) {
        mergeInfoVO.setRefundVO(refundVO);
        return mergeInfoVO;
    }

    private static <T> T log(Supplier<T> supplier) {
        long start = System.currentTimeMillis();
        T t = supplier.get();
        System.out.println(System.currentTimeMillis() - start + ":ms");
        return t;
    }

}
